#include "pwext.hpp"
#include <stdio.h>
#include <stdlib.h>
#include "ex05fc.cpp"

// [[ex05fd]]
// DEBUG descr A scoped class for turning the weak references into the strong ones.
template <typename target>
class scopegrab
{
public:
	scopegrab(weakref *ref, target *&result) : ref_(ref)
	{
		result = (target *)ref->grab();
	}
	~scopegrab()
	{
		ref_->release();
	}
protected:
	weakref *ref_;
private: 
	// prevent the default and copy constructors and
	// assignments
	scopegrab();
	scopegrab(const scopegrab &);
	void operator=(const scopegrab &);
};
// END

// DEBUG from
class mytarget : public reftarget
{
public:
	mytarget() :
		reftarget(this)
	{ }

	~mytarget()
	{
		invalidate();
	}
};

int main()
{
	mytarget *t = new mytarget;
	weakref *r = t->newweakref();
	{
		mytarget *tt;
		scopegrab<mytarget> scope(r, tt);
		if (tt) {
			fprintf(stderr, "target is still valid\n");
		}
	}
	delete t;
	return 0;
}

/* Sample result:
target is still valid
*/
